#include <windows.h>
#include <stdio.h>
#include <sql.h>
#include <sqltypes.h>
#include <sqlext.h>

/*******************************************************************
** initialize
**  - allocate environment handle
**  - allocate connection handle
**  - prompt for server, user id, & password
**  - connect to server
*******************************************************************/

int initialize(SQLHENV *henv,
	SQLHDBC *hdbc)
{
	SQLCHAR     server[SQL_MAX_DSN_LENGTH],
		uid[30],
		pwd[30];
	SQLRETURN   rc=0;

	SQLAllocEnv(henv);         /* allocate an environment handle   */
	if (rc != SQL_SUCCESS)
		check_error(*henv, *hdbc, SQL_NULL_HSTMT, rc);

	SQLAllocConnect(*henv, hdbc);  /* allocate a connection handle     */
	if (rc != SQL_SUCCESS)
		check_error(*henv, *hdbc, SQL_NULL_HSTMT, rc);

	printf("Enter Server Name:\n");
	gets(server);
	printf("Enter User Name:\n");
	gets(uid);
	printf("Enter Password Name:\n");
	gets(pwd);

	if (uid[0] == '\0')
	{
		rc = SQLConnect(*hdbc, server, SQL_NTS, NULL, SQL_NTS, NULL, SQL_NTS);
		if (rc != SQL_SUCCESS)
			check_error(*henv, *hdbc, SQL_NULL_HSTMT, rc);
	}
	else
	{
		rc = SQLConnect(*hdbc, server, SQL_NTS, uid, SQL_NTS, pwd, SQL_NTS);
		if (rc != SQL_SUCCESS)
			check_error(*henv, *hdbc, SQL_NULL_HSTMT, rc);
	}
}/* end initialize */


 /*******************************************************************/
int check_error(SQLHENV    henv,
	SQLHDBC    hdbc,
	SQLHSTMT   hstmt,
	SQLRETURN  frc)
{
	SQLRETURN   rc;

	//print_error(henv, hdbc, hstmt);

	switch (frc) {
	case SQL_SUCCESS: break;
	case SQL_ERROR:
	case SQL_INVALID_HANDLE:
		printf("\n ** FATAL ERROR, Attempting to rollback transaction **\n");
		rc = SQLTransact(henv, hdbc, SQL_ROLLBACK);
		if (rc != SQL_SUCCESS)
			printf("Rollback Failed, Exiting application\n");
		else
			printf("Rollback Successful, Exiting application\n");
		terminate(henv, hdbc);
		exit(frc);
		break;
	case SQL_SUCCESS_WITH_INFO:
		printf("\n ** Warning Message, application continuing\n");
		break;
	case SQL_NO_DATA_FOUND:
		printf("\n ** No Data Found ** \n");
		break;
	default:
		printf("\n ** Invalid Return Code ** \n");
		printf(" ** Attempting to rollback transaction **\n");
		SQLTransact(henv, hdbc, SQL_ROLLBACK);
		terminate(henv, hdbc);
		exit(frc);
		break;
	}
	return(SQL_SUCCESS);

}